package com.j2203.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Controller
public class PayController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Autowired
//    DonaItemService donaItemService;
//    @Autowired
//    DonaService donaService;
    //appid
    private final String APP_ID = "2021000121625085";
    //应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7Eu8M0uWQ3ZLZuZUofpzPnwqx78Z+/22/VkGiPCE5Ci1Pj/aVM0e+YaFprOx/8AgatpvVajEUPPRbF87wxNac8exIAvqLrmZouhXNgCrFdz1hjgdFZGfYS6QRu1dqT+drWtb+3+C7nNxWD0QaGhKqAJyDMraC2NPqSBjm4q1kHLMQRwrBNa8LfJQ0at9Es9uQSeQOOLj26GoptHDMyqQScsXnlWssVzLHXykshLQ/uhMoUI4JLQjjWG05L9KP1PFfhFx1g4iR0RFenpt8fFKKzqXntMT12Z89VHq2na1WhFF0GXBm42HZ+7O/gucZ6QH0nMhxWzW+qdiC4pzuPpjhAgMBAAECggEBALa2WmaTAQaJcqlWOdmQOAYMlvyNbLiTL5SGYZpb0jMMvo6L1FGLAVJvtqAo9eBLBw9YNUGu8vqKQjtKOKMuDVLCcn0u85hDoOA+h5brzFqLCJdkibN7ynUWA8wRxuId4rAWzA+ph6yWGxmu1VwNBRenezYk7N9FeUzEWBYBZUp1kiDPXkDE4UflwBFqLeSeX+OGDT+xJztpibFDIHceGp/QoAw9BtFZzSoA3Sc+lg4BPaC9JKzecsHOcfRxnHP7zOTQhgV+VWaA6lb5jcZJ/In/78dVDpNSMg2JFvcQRHMRDFGYPyiRWx15Ox0NIZppoKx0/drvn1Y2XMi3exz4rjUCgYEA+g6s2hEAOCJPvdar5lpYC+FjvECGAd0WszZ2vciAwx22mW4N8CDVk44FP/S9vl9ZRouS2K4GYOL7YE/pVvp7E+FPrWrv/HAg6m2jZwC4PFRgDgM2I6vwyQMV2MGM/rtMDDeCIT5/vd1z92kUIyJ93mqCGoLEFYCTvn6Y65vIKOMCgYEAv4US5qVr/Ra/pRWfhgU602xPA35fJK7lKNS41sx6aLBxk6cbRIPd71dvU85z+pr+pH1wOL7bQqaROmGbruTQmdslpYK1xWBOV63NmrvUdQgGTgzEATCQ5Uxo1zifa4CfHlLWcPpOPq5ui33KSDGW42mCmHaa9NE6EpTbxNBGFmsCgYEAwxZT8MW2wBS01cz3y/3MF2i+4Q4N/sI4hZUGSsZ0/sTdwxJDuYZEWpxAqEcPCcll403dQUN0In6z085Eo+FDyJzOBuQZW383ju3+v8ul8Rt63TPQN0Bb2NeZYcSPdeU2TYm48qrKCp0NbocCeO7d+HpsCrbeuE/Z9JLcR2UAYjUCgYAc8I/VmGOD/97/pA/R4ZJtBi2+WmcoFOF91P8FPiq1DQxsglDFfqOXmf+xiz3NPYSC+I1vla9uF9tUFhG/UMYQqaO7qc+rvoy4BQRPgFhvQsIpIxavE1ahv3UMKHs2dF4W5++NbNVL9XGw1FYvqIajYHsibLGnksISsrmuuMYOdwKBgQDDeotsCkgzX3BlVCPBlAlKy/XPe8HN3j5h76gg38Y1jmPJkbjUw/dN8hBKZuXaK0OpT/7e/R/HS86UBcN6DGHPHDmvvQQpPnMbckkzxV3rXBQGjEqISm40OaOzJLn2zH6KMrIO++evREfpt8/4ML5jQMasQDIq8xuxU9tzc34EGA==";
    private final String CHARSET = "UTF-8";
    // 支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAopnhJpsatvEzby3sG+NaeO3HAohSdPxrH1KiArk0VRHc3ExdmJhI0CE1P5vjAtmt2F5Gcetp3dRjjMOBbvGCF6uJsxQBQfFvOUZEpnTDJc6EfhrykwA2DeoAscfgB9v34aWBSLVkor0Bj7VVsCB6j+dNdFg5jfJJ7+o9Tu6WsXei1kBaI6YxYdG2FhLfQl03e+fAr2lHh0DQRVuQP7henshkmHxjXAjaO+mOpbGciVsAsIQs7BT2cIBtwgSxxuXYraQmAQQN24lEUgm4jUORjz5VJ9AyCs05b1y1EeQ9J05PqMmQI0DupmEqHXaOqwC/e7US3e8GRmVsbQ3V1CiGnQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://127.0.0.1/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/updateOrder";


    //必须加ResponseBody注解，否则spring会寻找thymeleaf页面
    @ResponseBody
    @RequestMapping("/pay/alipay")
    public String alipay(HttpSession session, Model model,
                         @RequestParam(value = "dona_money") float dona_money,
                         @RequestParam(value = "uid") int uid) throws AlipayApiException {
        //把dona_id项目id 放在session中
        session.setAttribute("dona_id",uid);

//        //生成订单号（支付宝的要求？）
//        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

//        String OrderNum = time+user;
        String OrderNum = stringRedisTemplate.opsForValue().get(uid + "");

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum,dona_money,"ghjk");
    }
    /*
参数1：订单号
参数2：订单金额
参数3：订单名称
 */
    //支付宝官方提供的接口
    private String sendRequestToAlipay(String outTradeNo,Float totalAmount,String subject) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }


}
